import {HttpClient, HttpParams} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import "rxjs/add/operator/catch";

@Injectable()
export class mysqlLogsService {
    apiUrl = 'http://127.0.0.1:9991/mysql';

    getLogs(PageIndex = 1, pageSize = 10, args?: any) {
        // fix laster version
        let param = new HttpParams().set('page', '' + PageIndex).set('rows', '' + pageSize);
        if (args) {
            Object.keys(args).forEach(key => {
                param = param.append(key, args[key]);
            });
        }

        let customParam = param;
        customParam = this.paramDataFormat("b_tm", customParam);
        customParam = this.paramDataFormat("e_tm", customParam);
        return this.http.get(this.apiUrl + '?' + customParam.toString())
            .catch(this.handleError);
    }

    handleError(error: any) {
        const errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }

    constructor(private http: HttpClient) {
    }

    paramDataFormat(keyField: string, param: HttpParams): HttpParams {
        if (param.has(keyField)) {
            let newMonth;
            let da = (new Date(param.get(keyField)));
            let year = da.getFullYear();
            let month = da.getMonth() + 1;
            if (month < 10) {
                newMonth = '0' + month
            }
            let date = da.getDate();
            let dateStr = [year, newMonth, date].join('-');
            param = param.set(keyField, dateStr)
        }
        return param;
    }

}
